<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
*	Page Library - simplifies management and loading of page data
*
*	@author			Timothy Wood (codearachnid@gmail.com)
*	@last_modified	August 4th, 2007
*
*/

class Contact {
	
	var $CI;

	function Contact() {
		$this->CI =& get_instance();
	}
	
	function validate()
	{
		$this->CI->load->library('validation');
		$rules['cn_name'] = "trim|required";
		$rules['cn_email'] = "trim|required|valid_email";
		$rules['cn_question'] = "trim|required";
		$this->CI->validation->set_rules($rules);

		$fields['cn_name']	= 'Name';
		$fields['cn_email']	= 'Email Address';
		$fields['cn_question']	= 'Questions';
		$this->CI->validation->set_fields($fields);
		if ($this->CI->validation->run() == FALSE)
		{
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}

	function email()
	{
		$this->CI->load->library('email');

		$config['mailtype'] = 'html';
		$this->CI->email->initialize($config);
		$full_list = '';
		$table_list = explode("|", $this->CI->input->post('call_table', TRUE));
		$field_list = explode("|", $this->CI->input->post('field_list', TRUE));
		
		foreach ($table_list as $table) {
			foreach ($field_list as $table_field) {
				$field = explode(".", $table_field);
				if($field[1] == null || $table != $field[0] || $this->isempty($this->CI->input->post($field[1]))) continue;
				$full_list .= '<b>'.$this->CI->input->post($field[1] . '_display') . ':</b> '.$this->CI->input->post($field[1]).'<br />';
			}
		}
		
		// send email to streamline
		$this->CI->email->clear();
		$this->CI->email->from($this->CI->input->post('cn_email', TRUE));
		$this->CI->email->to($this->CI->config->item('contact_us_email'));
		$this->CI->email->subject('Contact us from LifeSupplemented.org');
		$tmp_message =  'Here\'s what you were sent:<br /><br />'. $full_list;
		$this->CI->email->message($tmp_message);
		$this->CI->email->send();

		// send email to contactee
		$this->CI->email->clear();
		$this->CI->email->from($this->CI->config->item('contact_us_email'));
		$this->CI->email->to($this->CI->input->post('cn_email', TRUE));
		$this->CI->email->subject('Contact us from LifeSupplemented.org');
		$tmp_message =  'Life Supplemented appreciates your visit to our Web site and for taking your time to send us some information.<br /><br />'.
						'Here\'s what you sent us:<br /><br />'.$full_list;
		$this->CI->email->message($tmp_message);
		$this->CI->email->send();

	}
 
	function save()
	{
		if($this->validate()) {
			$this->CI->sitedb->push_data();
			$this->email();
		} else {
			$this->CI->view->set('validation_msg', 'show');
		}
	}


	/*
	 * 
	 * internal functions needed for the class 
	 * 
	 */
	function isempty($var) {
	  if (((is_null($var) || rtrim($var) == "") && $var !== false) || (is_array($var) && empty($var))) {
	    return true;
	  } else {
	    return false;
	  }
	} 
	
}

?>